<template>
  <!-- 搜索区域 -->
  <el-card shadow="never" class="henader-card">
    <div class="flx-row">
      <el-form :inline="true" :model="queryData" style="flex: 1">
        <!-- 物料条码搜索 -->
        <el-form-item label="物料条码：" label-width="120px">
          <el-input
            v-model="queryData.matCode"
            placeholder="请输入物料条码关键词"
            clearable
            class="input-width"
          />
        </el-form-item>

        <!-- 时间范围筛选 -->
        <el-form-item label="时间范围：" label-width="100px">
          <el-date-picker
            v-model="queryData.date"
            type="datetimerange"
            :shortcuts="shortcuts"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
          />
        </el-form-item>

        <!-- 分页大小选择 -->
        <el-form-item label="每页条数：" label-width="100px">
          <el-select
            v-model="queryData.size"
            @change="handleSizeChange"
            style="width: 120px"
          >
            <el-option label="10条/页" value="10" />
            <el-option label="20条/页" value="20" />
            <el-option label="50条/页" value="50" />
            <el-option label="100条/页" value="100" />
          </el-select>
        </el-form-item>
      </el-form>

      <div class="flex-right">
        <el-button type="primary" :icon="Search" @click="initData" class="ml20">
          搜索
        </el-button>
        <el-button
          type="primary"
          :icon="Download"
          @click="exportExcel"
          class="mr20"
        >
          导出数据
        </el-button>
      </div>
    </div>
  </el-card>

  <!-- 表格和分页部分 -->
  <el-card shadow="never">
    <el-table
      :data="tableData"
      :header-cell-style="{ backgroundColor: '#ecf5ff' }"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
      element-loading-text="加载中..."
      empty-text="暂无数据"
    >
      <!-- 表格列配置 -->
      <el-table-column
        v-for="item in tableColumns"
        :key="item.props"
        :prop="item.props"
        :label="item.label"
        :align="item.align"
        :width="item.width"
        :fixed="item.fixed"
        show-overflow-tooltip
      >
        <!-- 加工结果格式化 -->
        <template v-slot:default="scope" v-if="item.props === 'result'">
          <el-tag :type="scope.row.result ? 'success' : 'danger'">
            {{ scope.row.result ? "通过" : "未通过" }}
          </el-tag>
        </template>

        <!-- 时间格式化 -->
        <template 
          v-slot:default="scope" 
          v-if="item.props === 'createTime' || item.props === 'updataTime'"
        >
          <span>{{ formatDate(scope.row[item.props]) }}</span>
        </template>

        <!-- 工序数据（点击查看详情） -->
        <template v-slot:default="scope" v-if="item.props === 'datas'">
          <el-button 
            type="text" 
            @click="openDetailDialog(scope.row)"
            class="datas-btn"
            size="small"
          >
            查看数据
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      small
      background
      :page-size="queryData.size"
      layout="total, prev, pager, next, jumper"
      :total="total"
      class="mt-4"
      @current-change="handleCurrentChange"
    />
  </el-card>

  <!-- 详情弹窗 -->
  <el-dialog 
    title="生产工序详情" 
    v-model="dialogVisible" 
    width="80%" 
    top="5%"
    :before-close="handleDialogClose"
    :destroy-on-close="true"
  >
    <!-- 弹窗内容保持不变 -->
    <div class="dialog-toolbar">
      <el-button 
        type="text" 
        @click="toggleExpandAll"
        :icon="expandAll ? Minus : Plus"
      >
        {{ expandAll ? "收起全部" : "展开全部" }}
      </el-button>
    </div>

    <el-collapse 
      v-model="activePanels" 
      :accordion="false"
      style="max-height: 600px; overflow-y: auto; padding-right: 10px;"
    >
      <el-collapse-item 
        v-for="(process, processIndex) in processes" 
        :key="processIndex" 
        :name="processIndex"
      >
        <template #title>
          <div class="process-title">
            <span class="step-num">工序 {{ process.Step }}</span>
            <span class="station-name">{{ process.StationName || '未知工站' }}</span>
            <el-tag 
              :type="process.ResultFlag.toUpperCase() === 'OK' ?  'success' : 'danger'" 
              size="small"
              class="result-tag"
            >
              {{ process.ResultFlag.toUpperCase() }}
            </el-tag>
          </div>
        </template>

        <div class="process-base-info">
          <el-descriptions column="4" border size="small">
            <el-descriptions-item label="工站编号">{{ process.StationCode || '-' }}</el-descriptions-item>
            <el-descriptions-item label="进站状态">{{ process.MoveIn_OK === 'TRUE' ? '正常' : '异常' }}</el-descriptions-item>
            <el-descriptions-item label="出站状态">{{ process.MoveOut_OK === 'TRUE' ? '正常' : '异常' }}</el-descriptions-item>
            <el-descriptions-item label="出站时间">{{ process.MoveOutTime ? formatDate(process.MoveOutTime) : '-' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="params-table">
          <el-table 
            :data="process.DataLists" 
            border 
            size="small"
            style="width: 100%; margin-top: 10px;"
            empty-text="无参数数据"
          >
            <el-table-column prop="paramName" label="参数名称" width="200" />
            <el-table-column prop="paramCode" label="参数编码" width="180" />
            <el-table-column prop="realValue" label="实际值" width="150" />
          </el-table>
        </div>
      </el-collapse-item>
    </el-collapse>

    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import * as XLSX from "xlsx";
import { Search, Download, Plus, Minus } from "@element-plus/icons-vue";
import { getProductionDetailList } from "../../../api/modules/index";
import { onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { tableColumns } from "./options.js";

// 1. 查询参数
const queryData = ref({
  matCode: "",
  page: 1,
  size: 10,
  date: [],
});

// 2. 表格数据
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);

// 3. 弹窗相关变量
const dialogVisible = ref(false);
const currentRow = ref(null);
const expandAll = ref(false);
const activePanels = ref([]);
const processes = ref([]);

// 4. 分页处理
const handleSizeChange = (val) => {
  queryData.value.size = val;
  queryData.value.page = 1;
  initData();
};

const handleCurrentChange = (val) => {
  queryData.value.page = val;
  initData();
};

// 5. 初始化数据
const initData = () => {
  loading.value = true;
  
  // 格式化日期为UTC
  const formatUTCDate = (date) => {
    if (!date) return "";
    const d = new Date(date);
    return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(d.getUTCDate()).padStart(2, "0")} ${String(d.getUTCHours()).padStart(2, "0")}:${String(d.getUTCMinutes()).padStart(2, "0")}:${String(d.getUTCSeconds()).padStart(2, "0")}`;
  };

  const { date, ...restParams } = queryData.value;
  const params = {
    ...restParams,
    MatCode: restParams.matCode,
    StartTime: formatUTCDate(date?.[0]),
    EndTime: formatUTCDate(date?.[1]),
  };

  getProductionDetailList(params)
    .then((res) => {
      if (res.result === 1) {
        total.value = res.data.total;
        tableData.value = res.data.items || [];
      } else {
        ElMessage.error(res.message || "获取数据失败");
      }
    })
    .catch((err) => {
      ElMessage.error("网络错误，请重试");
      console.error(err);
    })
    .finally(() => {
      loading.value = false;
    });
};

// 6. 日期格式化
const formatDate = (isoString) => {
  if (!isoString) return "";
  const date = new Date(isoString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

// 7. 弹窗操作
const openDetailDialog = (row) => {
  currentRow.value = row;
  dialogVisible.value = true;
  parseDatas(row.datas);
};

// 解析datas字段
const parseDatas = (datasStr) => {
  try {
    const parsed = typeof datasStr === 'string' ? JSON.parse(datasStr) : datasStr || [];
    processes.value = Array.isArray(parsed) ? parsed : [parsed].map(process => ({
      ...process,
      DataLists: process.DataLists || []
    }));
    expandAll.value = false;
    activePanels.value = [];
  } catch (error) {
    processes.value = [{
      Step: 0,
      StationName: '数据解析失败',
      ResultFlag: 'ERROR',
      DataLists: [{
        paramCode: 'ERROR',
        paramName: '解析错误',
        realValue: '无法解析工序数据',
        checkResult: 0
      }]
    }];
    console.error("解析失败：", error);
    ElMessage.warning("工序数据格式错误");
  }
};

// 展开/收起全部
const toggleExpandAll = () => {
  expandAll.value = !expandAll.value;
  activePanels.value = expandAll.value 
    ? processes.value.map((_, i) => i) 
    : [];
};

// 关闭弹窗
const handleDialogClose = () => {
  dialogVisible.value = false;
  currentRow.value = null;
  processes.value = [];
};

// 8. 导出Excel
const exportExcel = () => {
  try {
    if (!tableData.value.length) {
      ElMessage.warning("当前页没有数据可导出");
      return;
    }

    const exportData = tableData.value.map((row) => ({
      "数据编号": row.id || "-",
      "物料条码": row.matCode || "-",
      "订单编号": row.orderCode || "-",
      "工站编号": row.stationId || "-",
      "工序步骤": row.step,
      // "工序数据": JSON.stringify(row.datas) || "-",
      "创建时间": formatDate(row.createTime),
      "更新时间": formatDate(row.updataTime),
    }));

    const data = XLSX.utils.json_to_sheet(exportData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, data, "生产详情记录");
    const fileName = `生产详情记录_${new Date()
      .toLocaleString()
      .replace(/[:/]/g, "-")}.xlsx`;
    XLSX.writeFile(wb, fileName);
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败", error);
    ElMessage.error("导出失败，请重试");
  }
};

// 9. 日期快捷选项
const shortcuts = [
  {
    text: "今天",
    value: () => [
      new Date(new Date().setHours(0, 0, 0, 0)),
      new Date(new Date().setHours(23, 59, 59, 999)),
    ],
  },
  {
    text: "昨天",
    value: () => [
      new Date(new Date().getTime() - 24 * 60 * 60 * 1000),
      new Date(new Date().setHours(23, 59, 59, 999) - 24 * 60 * 60 * 1000),
    ],
  },
  {
    text: "近7天",
    value: () => [
      new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000),
      new Date(),
    ],
  },
];

// 10. 页面加载初始化
onMounted(() => {
  initData();
});
</script>

<style lang="scss" scoped>
.henader-card {
  margin-bottom: 20px;
  padding: 15px 20px;
}

// 表单项目间距（强制覆盖默认样式）
:deep(.el-form-item) {
  margin-right: 15px !important;
  margin-bottom: 10px !important;
  margin-top: 10px;
}

// 补充表单行容器样式，确保整体对齐
:deep(.el-form--inline .el-form-item) {
  display: inline-flex;
  align-items: center;
  margin-right: 15px !important;
  margin-bottom: 10px !important;
}

// 调整标签与输入框的间距，与第一个表格保持一致
:deep(.el-form-item__label) {
  padding-right: 10px !important;
}

:deep(.el-form-item__content) {
  flex: 1;
}

// 输入框宽度
.input-width {
  width: 180px;
}

// 日期选择器宽度
:deep(.el-date-editor) {
  width: 300px;
}

// 分页样式
.mt-4 {
  float: right;
  text-align: right;
  margin-top: 20px;
  margin-bottom: 20px;
}

// 表格样式
:deep(.el-table .cell) {
  white-space: normal !important;
  word-break: break-all;
  line-height: 1.5;
}

// 其他原有样式保持不变...
.flx-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  width: 100%;
}

.flex-right {
  display: flex;
  align-items: center;
  margin-left: auto;
}

.ml20 {
  margin-left: 20px;
}

.mr20 {
  margin-right: 20px;
}

.datas-btn {
  padding: 0 !important;
  color: #409eff;
  &:hover {
    color: #6aa8ff;
    text-decoration: underline;
  }
}

.dialog-toolbar {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  text-align: right;
}

.process-title {
  display: flex;
  align-items: center;
  gap: 10px;

  .step-num {
    font-weight: bold;
    color: #1f2329;
  }

  .station-name {
    color: #333;
    flex: 1;
  }

  .result-tag {
    margin-left: auto;
  }
}

.process-base-info {
  margin: 10px 0;
  padding: 5px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.params-table {
  margin-top: 10px;

  :deep(.el-table) {
    border-top: 1px solid #ebeef5;

    .el-table__header-wrapper {
      background-color: #f5f7fa;
    }

    .el-table__cell {
      padding: 6px 0;
      font-size: 13px;
    }
  }
}

:deep(.el-collapse-item__header) {
  padding: 12px 20px;
  background-color: #fafafa;

  &:hover {
    background-color: #f0f2f5;
  }
}

:deep(.el-collapse-item__content) {
  padding: 10px 20px;
  border-top: 1px dashed #ebeef5;
}
</style>